package com.kuangstudy.aspect;

import com.kuangstudy.anno.AccessIpLimiter;
import com.kuangstudy.utils.ip.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author renyitong
 * @version 1.0.0
 * @createTime 2023年09月15日
 * @Description 使用切面 完成redis的lua脚本的 限流操作
 */
@Aspect
@Component
@Slf4j
public class AccessIpLimiterAspect implements Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private DefaultRedisScript<Long> ipLimitLua;

    /**
     * 定义切入点
     */
    @Pointcut("@annotation(com.kuangstudy.anno.AccessIpLimiter)")
    public void pointcut() {
    }

    /**
     * 定义通知和连接点
     */
    @Before("pointcut()")
    public void beforeLimit(JoinPoint joinPoint) {
        // 1：获取方法的签名作为key
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        AccessIpLimiter annotation = method.getAnnotation(AccessIpLimiter.class);
        // 2：如果没有增加accessLimiter注解说明不需要限流，直接返回
        if (annotation == null) {
            return;
        }
        // 获取限流缓存的key userId
        String key = annotation.key();
        // 获取限流缓存的限制次数
        Integer limit = annotation.limit();
        // 获取限流缓存的时间
        Integer timeout = annotation.timeout();

        // 获取方法的参数的类型，用&拼接参数
        Class<?>[] parameterTypes = method.getParameterTypes();
        String paramTypes = Arrays.stream(parameterTypes).map(Class::getName).collect(Collectors.joining("&"));

        // 获取请求对象和响应对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();

        // 获取用户请求地址
        String ipAddress = IpUtils.getIpAddr(request);
        log.info("切面客户端请求的IP地址是：{}", ipAddress);

        if (StringUtils.isBlank(key)) {
            // 获取方法所有的参数
            String name = method.getDeclaringClass().getName();
            // 获取方法的签名
            key = name + "#" + method.getName() + "#" + paramTypes + "#" + ipAddress;
            log.info("key is : {}", key);
        }

        // 调用lua脚本进行限流操作
        Long resultLong = stringRedisTemplate.execute(ipLimitLua, Arrays.asList(key), timeout.toString(), limit.toString());
        if (resultLong == 0) {
            throw new RuntimeException("客官,你慢点点击,我快要承受不住了!!!");
        }

        return;
    }

    /**
     * 排序
     * @return
     */
    @Override
    public int getOrder() {
        return -100;
    }
}
